package com.community.sqlapp.service;

import com.alibaba.fastjson.JSONObject;
import com.community.sqlapp.entity.TencentCosFile;
import com.community.sqlapp.mapper.TencentCosFileMapper;
import com.community.sqlapp.service.biz.InsetTestCaseToExcel;
import com.community.sqlapp.utils.FileExtension;
import com.community.sqlapp.utils.TencentCosUtil;
import com.qcloud.cos.COSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * xmind转换excel实现类
 */
@Service
public class XMindToExcelService {

    private static Logger logger = LoggerFactory.getLogger(XMindToExcelService.class);

    @Autowired
    private TencentCosFileMapper tencentCosFileMapper;
    @Autowired
    private TencentCosUtil tencentCosUtil;
    @Value("${tencent.cos.bucketname}")
    private String bucket;

    /**
     * 查询xmind用例数
     * @param file
     * @return
     */
    public JSONObject getXmindFiles(MultipartFile file){
        JSONObject jsonObject=new JSONObject();
        String originalFilename = file.getOriginalFilename();
        String xmindFileName = extractPrefix(originalFilename);
        String  newXmindFilename =xmindFileName + "_" + UUID.randomUUID().toString()+FileExtension.XMIND;
        try {
            // 1. 保存到临时文件
            File tempFile = File.createTempFile("upload_", FileExtension.XMIND);
            file.transferTo(tempFile);
            // 2. 上传到COS
            COSClient cosClient = tencentCosUtil.cosClient();
            // 生成唯一文件名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String key = "xmind_excel/" + UUID.randomUUID() + suffix;
            String cosPath = key + newXmindFilename;
            String url = TencentCosUtil.uploadFile(tempFile, cosPath, bucket, cosClient);
            // 3. 入库
            TencentCosFile cosFile = new TencentCosFile();
            cosFile.setFileName(newXmindFilename);
            cosFile.setFileUrl(url);
            tencentCosFileMapper.insert(cosFile);
            tempFile.delete();
            jsonObject.put("fileUrl", url);
            jsonObject.put("caseCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseNo());
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("state",1);
            jsonObject.put("message", ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage()));
        }
        return jsonObject;
    }
    /**
     * Xmind源文件上传
     * @param templateType  模版类型：ones、MeterSphere
     * @param file  源文件
     * @return
     */
    public JSONObject importFile(String templateType, MultipartFile file){
        JSONObject jsonObject=new JSONObject();
        if (file.isEmpty()) {
            jsonObject.put("state",1);
            jsonObject.put("message", ResponseEntity.badRequest().body("请选择要上传的文件"));
            return jsonObject;
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String xmindFileName = extractPrefix(originalFilename);
            String  newXmindFilename =xmindFileName + "_" + UUID.randomUUID().toString()+FileExtension.XMIND;
            // 1. 保存xmind到临时文件
            File tempXmind = File.createTempFile("upload_", FileExtension.XMIND);
            file.transferTo(tempXmind);
            // 2. 上传xmind到COS
            COSClient cosClient = tencentCosUtil.cosClient();
            // 生成唯一文件名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String key = "xmind_excel/" + UUID.randomUUID() + suffix;
            String cosXmindPath = key + newXmindFilename;
            String xmindUrl = TencentCosUtil.uploadFile(tempXmind, cosXmindPath, bucket, cosClient);
            // 3. 入库xmind
            TencentCosFile cosFileXmind = new TencentCosFile();
            cosFileXmind.setFileName(newXmindFilename);
            cosFileXmind.setFileUrl(xmindUrl);
            tencentCosFileMapper.insert(cosFileXmind);
            // 4. 生成excel
            String excelFileName = extractPrefix(newXmindFilename)+ FileExtension.XLSX;
            File tempExcel = File.createTempFile("excel_", FileExtension.XLSX);
            InsetTestCaseToExcel.setXMindFile(tempXmind);
            InsetTestCaseToExcel.setExcelFilePath(tempExcel.getAbsolutePath());
            InsetTestCaseToExcel.xMindToExcel(templateType);
            // 检查excel文件是否为空
            if (tempExcel.length() == 0) {
                throw new RuntimeException("xMind解析未生成有效excel内容，生成的excel文件为空，请检查xMind内容或解析逻辑！");
            }
            logger.info("生成excel文件大小: " + tempExcel.length());
            // 5. 上传excel到COS
            String excelKey = "xmind_excel/" + UUID.randomUUID() + ".xlsx";
            String cosExcelPath = excelKey;
            String excelUrl = TencentCosUtil.uploadFile(tempExcel, cosExcelPath, bucket, cosClient);
            logger.info("上传excel到COS: " + excelUrl);
            // 6. 入库excel
            TencentCosFile cosFileExcel = new TencentCosFile();
            cosFileExcel.setFileName(excelFileName);
            cosFileExcel.setFileUrl(excelUrl);
            tencentCosFileMapper.insert(cosFileExcel);
            // 7. 删除临时文件
            tempXmind.delete();
            tempExcel.delete();
            // 8. 返回url
            jsonObject.put("xmindUrl", xmindUrl);
            jsonObject.put("excelUrl", excelUrl);
            jsonObject.put("caseCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseNo());
            jsonObject.put("caseStepCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseSteps());
            jsonObject.put("verificationCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseCheckPointers());
        } catch (Exception e) {
            jsonObject.put("state",1);
            jsonObject.put("message",ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage()));
            return jsonObject;
        }
        return jsonObject;
    }
    /**
     * 字符串处理
     * @param input
     * @return
     */
    public static String extractPrefix(String input) {
        int index = input.indexOf(".xmind");
        return input.substring(0, index);
    }
}
